package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"math"
	"shop/models"
)

type ShopController struct {
	beego.Controller
}

type JsonR struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *ShopController) Add() {
	name := c.GetString("name")
	typed := c.GetString("typed")
	author := c.GetString("author")
	address := c.GetString("address")

	shop := models.Shop{
		Name:    name,
		Typed:   typed,
		Author:  author,
		Address: address,
	}

	err := models.DB.Create(&shop).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}

func (c *ShopController) Upload() {
	file, header, err := c.GetFile("img")
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "文件查询失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	if header.Size > 2*1024*1024 {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "文件超过2MB",
			Data: nil,
		}
		c.ServeJSON()
		return
	}

	defer file.Close()
	path := "static/img/" + header.Filename
	c.SaveToFile("img", path)
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "上传失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		Img := "http://127.0.0.1:8080/" + path
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "上传成功",
			Data: Img,
		}
		c.ServeJSON()
	}
}

func (c *ShopController) List() {
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)
	name := c.GetString("name")
	query := models.DB.Model(&models.Shop{})
	if name != "" {
		query = query.Where("name like ?", "%"+name+"%")
	}
	var count int64
	models.DB.Model(&models.Shop{}).Count(&count)
	sumpage := int(math.Ceil(float64(count) / float64(size)))
	offset := (page - 1) * size
	var shop []models.Shop
	err := models.DB.Offset(offset).Limit(size).Find(&shop).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "展示失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		pageData := make(map[string]interface{})
		pageData["shop"] = shop
		pageData["sumpage"] = sumpage

		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "展示成功",
			Data: pageData,
		}
		c.ServeJSON()
	}
}

func (c *ShopController) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Delete(models.Shop{}, id).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
